#include "monitor_irq.h"

//监测变动，并执行相应的操作
void monitor_irq_block(const char* fd_path,fun callback){

    //打开监测的文件
    int fd = open(fd_path,O_RDONLY);
    if(fd<0)
    {
        printf("open %s failed!\n",fd_path);  
        exit(99);
    }

    struct pollfd fdset;
    memset(&fdset,0x00,sizeof(struct pollfd));
    fdset.fd = fd;
    fdset.events = POLLPRI;//事件类型
    fdset.revents = 0;

    int ret = poll(&fdset, 1, -1);//监听，无限期等待

    switch (ret)
    {
    case 1:
        //出现事件
        close(fd);
        //出现断电后，需要执行的操作
        callback();
        break;
    case -1:
        //发生错误
        exit(99);
        break;
    default:
        break;
    }
}

//监控IO是否有事件发生
int poll_value(const char* fd_path,unsigned int is_block_time){
    int fd=open(fd_path,O_RDONLY);
    if(fd<0)
    {
        printf("open '%s' failed!\n",fd_path);  
        return -1;
    }

    struct pollfd fds[1];
    memset(&fds,0x00,sizeof(fds));
    fds[0].fd=fd;
    fds[0].events=POLLPRI | POLLOUT;

    int ret = poll(fds,1,is_block_time);
    if(ret<0)
    {
        printf("poll failed!\n");
        return -1;
    }else if(ret == 0){
        printf("poll outtime!\n");
        return -2;
    }else{
        //发生跳变
        if(fds[0].revents & (POLLPRI | POLLOUT))
        {
            printf("发生跳变！！！~~\n\r");
            return 1;
        }else{
            printf("没有发生跳变！！！~~\n\r");
            return 0;
        }
    }
}

void AAA(){
    printf(">>>monitor_irq\n\r");
}

